package com.yc.taixin.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * SpringMVC 登录拦截器
 */
public class LoginInterceptor implements HandlerInterceptor {
	private static final Logger log = LoggerFactory.getLogger(LoginInterceptor.class);

		/*//controller执行后且视图返回后调用此方法
		public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
				throws Exception {
			System.out.println("返回视图前  后处理");
		}
		//controller执行后但未返回视图前调用此方法
		public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
				throws Exception {
			System.out.println("未返回视图前 后处理....");
		}*/

	// controller执行前调用此方法
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj) throws Exception {
		try {
			if (request.getSession().getAttribute("user") != null) {
				return true;
			}
//			response.sendRedirect(request.getContextPath() + "/user/login");
			request.getRequestDispatcher("/user/login").forward(request, response);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return false;//如果设置为false时，被请求时，拦截器执行到此处将不会继续操作
	}
}